import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;

public class Sender implements Runnable {

	private Message msg;
	private ServerProfile recipient;

	public Sender(Message msg, ServerProfile recipient) {
		this.msg = msg;
		this.recipient = recipient;
		new Thread(this, msg.getSender() + " " + msg.getId()).start();
	}

	@Override
	public void run() {
		ServerProfile r = recipient;
		Random rnd = new Random();
		int avgDelay = Server.profile.getDelay(r);
//		System.out.println(Server.profile
//				+ " sends " + r + " with delay " + avgDelay);
		// Randomize the delays surrounding average delay
		if (avgDelay != 0) {
			try {
				Thread.sleep(Math.abs(rnd.nextInt()) % (avgDelay * 2));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		try (Socket client = new Socket(r.getIp(), r.getPort())) {
			
			OutputStream outToServer = client.getOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(outToServer);
			out.writeObject(msg);
			out.flush();
		} catch (IOException e) {
			System.err.println("Sender: Server " + r + " is not found");
		}
	}
}
